/*
 * Copyright (c) 2020. André Mion
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.andremion.louvre.preview;

import com.andremion.louvre.CheckRadioView;
import com.andremion.louvre.ResourceTable;
import com.andremion.louvre.util.transition.MediaSharedElementCallback;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.github.chrisbanes.photoview.PhotoView;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.AttrHelper;
import ohos.agp.components.PageSliderProvider;
import ohos.utils.net.Uri;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class PreviewAdapter extends PageSliderProvider {
    interface Callbacks {
        void onCheckedUpdated(boolean checked);

        void onMaxSelectionReached();
    }

    static List<Uri> mSelection;
    private final PreviewActivity mActivity;
    private final LayoutScatter mInflater;
    private final CheckRadioView mCheckbox;
    private final MediaSharedElementCallback mSharedElementCallback;
    private PreviewAdapter.Callbacks mCallbacks;
    private int mMaxSelection;
    private int mInitialPosition;
    private boolean mDontAnimate;
    private int mCurrentPosition = -1;
    private List<Uri> mImages = new ArrayList<>();

    PreviewAdapter(PreviewActivity activity,
                   CheckRadioView checkbox,
                   MediaSharedElementCallback sharedElementCallback,
                   List<Uri> selection) {
        mActivity = activity;
        mInflater = activity.getWindow().getLayoutScatter();
        mCheckbox = checkbox;
        mSharedElementCallback = sharedElementCallback;
        mSelection = selection;
        mDontAnimate = true;
    }

    void setCallbacks(PreviewAdapter.Callbacks callbacks) {
        mCallbacks = callbacks;
    }

    void setMaxSelection(int maxSelection) {
        mMaxSelection = maxSelection;
    }

    void setInitialPosition(int position) {
        mInitialPosition = position;
    }

    void swapData(List<Uri> mImages) {
        this.mImages = mImages;
        PreviewAdapter.this.notifyDataChanged();
    }

    @Override
    public int getCount() {
        if (mImages != null) {
            return mImages.size();
        } else {
            return 0;
        }
    }

    @Override
    public Object createPageInContainer(ComponentContainer componentContainer, int position) {

        Component component = LayoutScatter.getInstance(componentContainer.getContext())
                .parse(ResourceTable.Layout_page_item_preview, componentContainer, false);
        Uri data = getData(position);
        int screenWidth = AttrHelper.fp2px(componentContainer.getContext()
                .getResourceManager().getDeviceCapability().width, componentContainer.getContext());
        int screenHeight = AttrHelper.fp2px(componentContainer.getContext()
                .getResourceManager().getDeviceCapability().height, componentContainer.getContext());
        ComponentContainer.LayoutConfig layoutConfig = new ComponentContainer.LayoutConfig(screenWidth, screenHeight);

        PhotoView imageView = (PhotoView) component.findComponentById(ResourceTable.Id_image);
        imageView.setLayoutConfig(layoutConfig);
        Glide.with(mActivity)                             //配置上下文
                .load(Uri.parse(data.toString())) //设置图片路径(fix #8,文件名包含%符号 无法识别和显示)
                .diskCacheStrategy(DiskCacheStrategy.NONE)//缓存全尺寸
                .skipMemoryCache(true)
                .into(imageView);
        componentContainer.addComponent(component);
        return component;
    }

    @Override
    public void destroyPageFromContainer(ComponentContainer componentContainer, int i, Object o) {
        Component component = (Component) o;
        componentContainer.removeComponent(component);
    }

    @Override
    public boolean isPageMatchToObject(Component component, Object object) {
        return component == object;
    }


    Uri getData(int position) {
        return mImages.get(position);
    }

    /**
     * isSelected
     * @param position Position
     * @return Boolean
     */
    public boolean isSelected(int position) {
        Uri data = getData(position);
        return mSelection.contains(data);
    }

    void selectCurrentItem(int mCurrentPosition) {
        boolean selectionChanged = handleChangeSelection(mCurrentPosition);
        if (selectionChanged) {
            notifyDataChanged();
        }
        if (mCallbacks != null) {
            if (selectionChanged) {
                mCallbacks.onCheckedUpdated(isSelected(mCurrentPosition));
            } else {
                mCallbacks.onMaxSelectionReached();
            }
        }
    }

    List<Uri> getSelection() {
        return new LinkedList<>(mSelection);
    }

    private boolean handleChangeSelection(int position) {
        Uri data = getData(position);
        if (!isSelected(position)) {
            if (mSelection.size() == mMaxSelection) {
                return false;
            }
            mSelection.add(data);
        } else {
            mSelection.remove(data);
        }
        return true;
    }
}
